#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include "glm.h"

#if defined (__APPLE__) || defined(MACOSX)
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif

typedef enum { RED, GREEN, BLUE, GRAY} tColorChannel;

unsigned char* image = NULL; 
unsigned char* imageNormal = NULL; // image file
unsigned char* imageRed = NULL;  
unsigned char* imageGray = NULL;  
unsigned char* imageBlue = NULL;  
unsigned char* imageGreen = NULL;  
int iheight, iwidth;



void init() {

     glClearColor( 0.0f, 0.0f, 0.0f, 0.0 );
	 glShadeModel(GL_FLAT);
     glPixelStorei( GL_UNPACK_ALIGNMENT, 1);
}


void display( void ) {

   glClear( GL_COLOR_BUFFER_BIT );

   glDrawPixels( iwidth, iheight, GL_RGB, GL_UNSIGNED_BYTE, image );

   glutSwapBuffers();
}


void reshape( GLsizei w, GLsizei h )
{
  glViewport( 0, 0, w, h );
  glMatrixMode( GL_PROJECTION );
  glLoadIdentity();
  glOrtho( 0, w, 0, h, -1.0, 1.0 );
  glMatrixMode( GL_MODELVIEW );
}

//Função que invete a imagem
void inverteImagem(){
	unsigned char* aux = (unsigned char*)malloc(sizeof(unsigned char));
	int tamanhoLinha = iwidth * 3;
	int linha = -1;
	int pos = 0;
	int posLinha = 0;
	int altura = iheight -1;
	int tamanhoVetor = iwidth*iheight*3;
	
	int linhaMax = (altura -1 )/2;
	
	for(pos = 0; linha <= linhaMax; pos++){
		if(pos % tamanhoLinha == 0){
			posLinha = 0;
			linha++;
		}
		aux[0] = image[pos];
		image[pos] = image[(((altura - linha) * tamanhoLinha) + posLinha)];
		image[(((altura - linha) * tamanhoLinha) + posLinha)] = aux[0];
		posLinha++;
	}
	free(aux);
	
	
}

//Implementar nesse fim de semana
			
void retiraComponentes(char collor){
	
	
}


void tomCinza(){
	
	
}
			
	
	


void keyboard(unsigned char key, int x, int y)
{
	switch(key) {
		case 27		: 	exit(0);
						break;
		case 'i'    :inverteImagem();
		case 'I'    :
		             break;
		case 'p'	:
		case 'P'	: 	
						printf("Image size => %d x %d\n", iheight, iwidth);
						break;
		}
		
	glutPostRedisplay();
}


int main(int argc, char **argv) {


char* filename = "PPM/fishermen.ppm";

    if (argc > 1)
		filename = argv[1];
		
	printf("%s\n", filename);

    image = glmReadPPM(filename, &iwidth, &iheight);
    
    if (!image)
        exit(0);

    glutInit(&argc, argv);
    glutInitDisplayMode ( GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize ( iwidth, iheight);
    glutInitWindowPosition (10, 10);
    glutCreateWindow ( argv[1]);

    init();

	glutDisplayFunc( display );
    glutReshapeFunc(reshape);
	glutKeyboardFunc(keyboard);

    glutMainLoop();

    return 0;
}


